<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <SmForm
        ref="queryFormRef"
        :inline="true"
        label-width="150px"
        v-model="queryParams"
        :options="searchFormOptions"
        :getModelValue="getSearchFormData"
      >
        <template #action>
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </template>
      </SmForm>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['sys:dept:add']"
            type="success"
            icon="plus"
            @click="openForm('create')"
          >
            新增
          </el-button>
          <!-- <el-button
            v-hasPerm="['sys:dept:delete']"
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button> -->
        </div>
      </div>

      <SmTable
        isSelection
        border
        :loading="loading"
        :options="tableOptions"
        :data="list"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        :pagination="false"
        @selection-change="handleSelectionChange"
      >
        <template #operate="{ scope }">
          <!-- <el-button
            v-hasPerm="['sys:dept:add']"
            type="primary"
            link
            size="small"
            icon="plus"
            @click.stop="openForm('create', scope.row.id)"
          >
            新增
          </el-button> -->
          <el-button
            v-hasPerm="['sys:dept:edit']"
            type="primary"
            link
            size="small"
            icon="edit"
            @click.stop="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPerm="['sys:dept:delete']"
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </SmTable>
    </el-card>

    <OpenForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

import DeptAPI, { DeptVO, DeptForm, DeptQuery } from "@/api/system/dept-api";
import { useTable } from "./hooks/useTable";
import { useSearchForm } from "./hooks/search";
import OpenForm from "./components/OpenForm.vue";

const deptFormRef = ref();

const selectIds = ref<number[]>([]);

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<DeptVO[]>();
const deptOptions = ref<OptionType[]>();
const formData = reactive<DeptForm>({
  status: 1,
  parentId: "0",
  sort: 1,
});

// // 查询部门
// function handleQuery() {
//   loading.value = true;
//   DeptAPI.getList(queryParams).then((data) => {
//     deptList.value = data;
//     loading.value = false;
//   });
// }

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   handleQuery();
// }

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开部门弹窗
 *
 * @param parentId 父部门ID
 * @param deptId 部门ID
 */
async function handleOpenDialog(parentId?: string, deptId?: string) {
  // 加载部门下拉数据
  const data = await DeptAPI.getOptions();
  deptOptions.value = [
    {
      value: "0",
      label: "顶级部门",
      children: data,
    },
  ];

  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改部门";
    DeptAPI.getFormData(deptId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增部门";
    formData.parentId = parentId || "0";
  }
}

// 提交部门表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        DeptAPI.update(deptId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DeptAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除部门
function handleDelete(deptId?: number) {
  const deptIds = [deptId || selectIds.value].join(",");

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.status = 1;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

const {
  tableOptions,
  list,
  total,
  loading,
  queryParams,
  getList,
  handleQuery,
  handleResetQuery,
  queryFormRef,
  formRef,
  openForm,
} = useTable();

const { getSearchFormData, searchFormOptions } = useSearchForm(handleQuery, queryParams);

onMounted(() => {
  getList();
  // handleQuery();
});
</script>
